package base

import (
	"time"
	"github.com/sirupsen/logrus"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"github.com/onrik/logrus/filename"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/rifflock/lfshook"
)

// 数据库连接
var Db *sqlx.DB

func Init() {
	initLog()
	initDB()
}

// 初始化数据库配置
func initDB() {
	var err error
	Db, err = sqlx.Connect("mysql",
		"root:chaoyer43@tcp(www.chaoyer.com:3306)/ghost_assist?parseTime=true&loc=Asia%2FShanghai")
	if err != nil {
		logrus.Fatal(err)
	}
	// Db.Mapper = reflectx.NewMapperFunc("json", strings.ToLower)
}

// 初始化日志配置
func initLog() {
	logrus.SetFormatter(&logrus.TextFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
		ForceColors:     true,
		FullTimestamp:   true,
	})

	// 报错 文件、行号
	fileLineNum := filename.NewHook()
	fileLineNum.Field = "at"
	logrus.AddHook(fileLineNum)

	// info滚动日志
	infoPath := "/data/logs/log/info.log"
	infoWriter,_ := rotatelogs.New(
		infoPath+".%Y%m%d%H%M",
		rotatelogs.WithLinkName(infoPath),
		rotatelogs.WithMaxAge(24*30*time.Hour),   // 存留30天
		rotatelogs.WithRotationTime(24*time.Hour),  // 一天切割
	)

	// error滚动日志
	errPath := "/data/logs/err/err.log"
	errWriter,_ := rotatelogs.New(
		errPath+".%Y%m%d%H%M",
		rotatelogs.WithLinkName(errPath),
		rotatelogs.WithMaxAge(24*30*time.Hour),
		rotatelogs.WithRotationTime(24*time.Hour),
	)

	logrus.AddHook(lfshook.NewHook(
		lfshook.WriterMap{
			logrus.DebugLevel:infoWriter,
			logrus.InfoLevel:  infoWriter,
			logrus.FatalLevel:errWriter,
			logrus.ErrorLevel: errWriter,
		},
		&logrus.TextFormatter{
			TimestampFormat: "2006-01-02 15:04:05",
			QuoteCharacter:" ",
		},
	))
}
